import 'dart:convert';
import 'package:chi_med_det_flutter/url.dart';
import 'package:chi_med_det_flutter/userinfo.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:provider/provider.dart';

class LoginPage extends StatelessWidget {
  LoginPage({super.key});

  final TextEditingController _accountController = TextEditingController();
  final TextEditingController _passwordController = TextEditingController();

  void showSnakeBar(BuildContext context, String content) {
    final snackBar = SnackBar(
      content: Text(content),
      duration: Duration(seconds: 3),
      action: SnackBarAction(label: "知道了", onPressed: () {}),
    );
    ScaffoldMessenger.of(context).showSnackBar(snackBar);
  }

  Future<Map<String, dynamic>> login(String account, String password) async {
    // 使用模拟器时，主机名不能使用localhost或者127.0.0.1
    final url = Uri.parse(URL.LOGIN);
    final response = await http.post(
      url,
      headers: const {'Content-Type': 'application/json'},
      body: jsonEncode({'account': account, 'password': password}),
    );
    Map<String, dynamic> res = jsonDecode(response.body);
    return res;
  }

  void onLogin(BuildContext context) {
    final String account = _accountController.text.trim();
    final String password = _passwordController.text.trim();

    if (account.isEmpty || password.isEmpty) {
      showSnakeBar(context, "用户名与密码均不能为空");
    } else {
      login(account, password).then((value) {
        if (context.mounted) {
          if (value['code'] == 0) {
            showSnakeBar(context, "登录成功");
            Navigator.pushNamed(context, '/main');
            final UserInfo userInfo = Provider.of<UserInfo>(
              context,
              listen: false,
            );
            userInfo.setAccount(account);
            _accountController.clear();
            _passwordController.clear();
          } else {
            showSnakeBar(context, value['msg']);
            _accountController.clear();
            _passwordController.clear();
          }
        }
      });
    }
  }

  void onSignup(BuildContext context) {
    Navigator.pushNamed(context, '/signup');
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        title: Text('中医体质检测系统', style: TextStyle(fontWeight: FontWeight.bold)),
      ),
      body: Stack(
        children: [
          Positioned(
            top: 50,
            left: 30,
            child: const Text(
              "欢迎来到中医体质检测系统",
              style: TextStyle(
                fontSize: 24,
                color: Colors.purple,
                fontWeight: FontWeight.bold,
              ),
            ),
          ),
          Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: <Widget>[
                FractionallySizedBox(
                  widthFactor: .6,
                  child: TextField(
                    controller: _accountController,
                    maxLength: 12,
                    maxLines: 1,
                    textAlign: TextAlign.start,
                    textAlignVertical: TextAlignVertical.center,
                    decoration: InputDecoration(
                      hintText: "请输入账号",
                      prefixIcon: Icon(Icons.person),
                    ),
                  ),
                ),
                SizedBox(height: 10),
                FractionallySizedBox(
                  widthFactor: .6,
                  child: TextField(
                    controller: _passwordController,
                    obscureText: true,
                    maxLength: 12,
                    maxLines: 1,
                    textAlign: TextAlign.start,
                    textAlignVertical: TextAlignVertical.center,
                    decoration: const InputDecoration(
                      hintText: "请输入密码",
                      prefixIcon: Icon(Icons.lock),
                    ),
                  ),
                ),
                SizedBox(height: 20),
                FractionallySizedBox(
                  widthFactor: .5,
                  child: Row(
                    children: [
                      Expanded(
                        child: TextButton(
                          onPressed: () {
                            onLogin(context);
                          },
                          style: ButtonStyle(
                            foregroundColor: WidgetStateProperty.all(
                              Colors.white,
                            ),
                            backgroundColor:
                                WidgetStateProperty.resolveWith<Color>((
                                  Set<WidgetState> states,
                                ) {
                                  if (states.contains(WidgetState.pressed)) {
                                    return Colors.accents.first;
                                  }
                                  return Colors.purple;
                                }),
                          ),
                          child: const Text(
                            "登录",
                            style: TextStyle(
                              fontWeight: FontWeight.bold,
                              fontSize: 18,
                            ),
                          ),
                        ),
                      ),
                      SizedBox(width: 15),
                      Expanded(
                        child: TextButton(
                          onPressed: () {
                            onSignup(context);
                          },
                          style: ButtonStyle(
                            foregroundColor: WidgetStateProperty.all(
                              Colors.black,
                            ),
                            backgroundColor:
                                WidgetStateProperty.resolveWith<Color>((
                                  Set<WidgetState> states,
                                ) {
                                  if (states.contains(WidgetState.pressed)) {
                                    return Colors.lightGreen.shade200;
                                  }
                                  return Colors.lightBlue.shade200;
                                }),
                          ),
                          child: const Text(
                            "注册",
                            style: TextStyle(
                              fontWeight: FontWeight.bold,
                              fontSize: 18,
                            ),
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }
}
